<?php

namespace app\api\controller;

use app\common\controller\Api;
use addons\epay\library\Service as EpayService;
use EasyWeChat\Foundation\Application as WXPAY_APP;
use EasyWeChat\Payment\Order as WXPAY_ORDER;
use addons\third\model\Third;
use think\Config;
use think\Db;
use app\admin\model\Cource;
use app\common\model\Cangku; 
use app\common\model\Newmyplant; 
use app\admin\model\My_props;
use app\common\model\Usedaoju;
/**
 * 首页接口
 */
class Index extends Api
{
    // protected $noNeedLogin = ['mp3_detail','index','mp3_list'];
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];

    public function _initialize()
    {
        parent::_initialize();
        $this->user_id = $this->auth->id;
        $this->model = new \app\common\model\Order;
        // $this->user_id = 2;
    }  

     /**
     * 首页获取数据
     * @ApiSummary  (my_data是个人信息，index是六块地的种子列表，健名是location的位置)
     * @ApiMethod   (POST)
     * @ApiRoute    (/api/index/index)
     * @ApiReturn({
{
  "code": 1,
  "msg": "请求成功",
  "time": "1606268129",
  "data": {
    "my_data": {//个人信息
      "avatar": "http://vicky.nongchang2.com/assets/img/avatar.png",
      "experience": "1209.00",//经验值
      "discount": "9.40",//折扣值
      "nickname": "u103",
      "land_num": 3,//土地数量
      "level": "6"//当前会员等级
    },
    "index": {
      "1": {
        "id": 8,
        "name": "测试2种子",
        "user_id": 103,
        "image": "https://nongchang.bidou88.cn/uploads/20200911/8759a5404c4deca3bdf5310d51565a79.jpg",
        "shop_id": 2,
        "now_exp": "0.00",//当前能量值
        "location": "1",
        "not_pick_num": "0.00",//未采摘果实数量（斤）
        "shengyu": "240.00",//距离下一次成熟还有多少能量值
        "createtime": 1606268061,
        "shou_level": 0,//成熟阶段值，-1代表已经收获完，没有下一收获等级了。
        "per": "0.00",//成熟百分比
        "next_exp": "240.00"
      },
      "6": {
        "id": 7,
        "name": "测试种子",
        "user_id": 103,
        "image": "/assets/img/qrcode.png",
        "shop_id": 1,
        "now_exp": "0.00",
        "location": "6",
        "not_pick_num": "1.00",
        "shengyu": "240.00",
        "createtime": 1606209318,
        "shou_level": 0,
        "per": "0.00",
        "next_exp": "240.00"
      }
    }
  }
}
     })
     */
    public function index(){
        $return['my_data'] = Db::name('user')->where('id',$this->user_id)->field('avatar,experience,discount,nickname,land_num,level')->find();

        $return['index'] = Db::name('new_my_plant')->where(['user_id'=>$this->user_id])->select();
        $return['index'] = array_column($return['index'], null,'location');        
        $this->success('请求成功',$return);
    }

    /**
     * 我的仓库
     * @ApiSummary  (有抵用券，种子和果实（按斤算）三个类别)
     * @ApiMethod   (POST)
     * @ApiRoute    (/api/index/my_warehouse)
     * @ApiReturn({
      })
     */
    public function my_warehouse(){
        $data = Db::name('cangku')->where('user_id',$this->user_id)->select();
       
        $return['diyong'] = array_merge(array_filter($data,function($value){
                  if($value['status']=='diyong')
                    return true;
                }));
        $return['zhongzi'] = array_merge(array_filter($data,function($value){
                  if($value['status']=='zhongzi')
                    return true;
                }));
        $return['guoshi'] = array_merge(array_filter($data,function($value){
          if($value['status']=='guoshi')
            return true;
        }));
   
        $this->success('我的仓库、粮仓',$return);
    }

     /**
     * 浇水除草除虫施肥
     * @ApiSummary  (返回msg提示)
     * @ApiMethod   (POST)
     * @ApiRoute    (/api/index/use_props)
     * @ApiParams   (name="location",type=int,required=true,description="位置")
     * @ApiParams   (name="type",type=string,required=true,description="浇水:jiaoshui,除虫:chuchong,除草:chucao,施肥:shifei")
     */
    public function use_props(){
        
        $param['user_id'] = $this->user_id;
        $location = input('location');
        $type = input('type');

        $Newmyplant = new Newmyplant();
        $My_index_data = $Newmyplant->where(['location'=>$location,'user_id'=>$this->user_id])->find();
        if(empty($My_index_data))$this->error('当前土地没植物');
        $Usedaoju = new Usedaoju;

        switch (input('type')) {
          case 'jiaoshui':
            $prop_status = 3;
            break;
          case 'shifei':
            $prop_status = 4;
            break;
          case 'chuchong':
            $prop_status = 2;
            break;
          case 'chucao':
            $prop_status = 1;
            break;
        }

        $daoju_data = Db::name('new_prop')->where('id',$prop_status)->find();//不同道具不同限制

        $user_history = $Usedaoju->where(['user_id'=>$this->user_id,'status'=>input('type')])->find();//使用道具记录
        $now_date = date('Y-m-d',time());
        if(!empty($user_history)){
          $user_history_date = date('Y-m-d',$user_history['updatetime']);
          if($user_history_date!==$now_date){
            $user_history->save(['num'=>1,'updatetime'=>time()]);//如果不是当天数据，则修改日期为当天，次数变为一次
          }else{
            $now_num = $user_history['num']+1;
            if($now_num>$daoju_data['use_num'])$this->error('今日次数有限');
            $user_history->setInc('num');//增加使用次数
          }
        }else{
         $Usedaoju->insert(['user_id'=>$this->user_id,'status'=>input('type'),'updatetime'=>time()]);
        }
        Db::name('user')->where('id',$this->user_id)->setInc('experience',$daoju_data['add_exp']);//增加自己经验值
        //增加自己经验值后执行判断是否有升级
        $this->up_action();

        $new_exp = $daoju_data['reduce_hour']+$My_index_data['now_exp'];//先增加经验值，下面再判断是否符合升级条件

        $next_level = $My_index_data['shou_level'];//destination_json是以0为开始的

        $destination_json = Db::name('shop')->where('id',$My_index_data['shop_id'])->value('destination_json');
        
        $level_array = json_decode($destination_json,true);
        $next_exp = $level_array[$next_level]['exp'];

        $update['now_exp'] = $new_exp;//新增后的经验值
        if($new_exp>=$next_exp){//满足升级条件,1、增加果实斤数2、修改为完结状态
          $get_weigh = $level_array[$next_level]['get_weigh'];//升级可获得多少斤

          $update['not_pick_num'] = $get_weigh+$My_index_data['not_pick_num'];//增加未采摘数量
          
          //判断是否有下一级别
          if(array_key_exists($next_level+1, $level_array)){
            //还有下个目标
            $update['new_exp'] = $update['shengyu'] = $level_array[$next_level+1]['exp'];//新剩余
            $update['shou_level'] = $next_level+1;//新等级
            $update['per'] = 0.00;

            $return_text = '收获到'.$My_index_data['name'].$get_weigh.'斤,进入到下一发育期';
          }else{//没有下一个目标了,将shou_level 改为-1代表已全部收成
            $update['shou_level'] = -1;
            $update['per'] = 1;
            
            $return_text = '收获到'.$My_index_data['name'].$get_weigh.'斤,植被已全部收成可以挖掉了';
          }

        }else{//还没满足升级条件
          $update['shengyu'] = $My_index_data['shengyu']-$daoju_data['reduce_hour'];//新剩余
          $update['per'] = round(($new_exp/$My_index_data['next_exp']),2);
          $return_text = '距离收成还有'.$update['shengyu'];
        }

        $My_index_data->save($update);

        $this->success($return_text);
    }

    /**
     * 挖掉植被和采摘果实
     * @ApiSummary  ()
     * @ApiMethod   (POST)
     * @ApiRoute    (/api/index/wadiao)
     * @ApiParams   (name="location",type=int,required=true,description="位置")
     * @ApiParams   (name="status",type=string,required=true,description="caizhai：采摘.wadiao:挖掉")
     */
     public function wadiao(){
      $param = input();
      $location = $param['location'];
      $status = $param['status'];

      $now_location_data = Db::name('new_my_plant')->where(['user_id'=>$this->user_id,'location'=>$location])->find();
      if(empty($now_location_data))$this->error('该地没有植被');

      switch ($status) {
        case 'wadiao':
          $add_exp = Db::name('new_prop')->where('id',8)->value('add_exp');
          Db::name('user')->where('id',$this->user_id)->setInc('experience',$add_exp);

          $return_text = '成功挖掉，个人经验值增加'.$add_exp;

          Db::name('new_my_plant')->where(['user_id'=>$this->user_id,'location'=>$location])->delete();
          break;
        
        case 'caizhai':
          $if_exist_cangku = Db::name('cangku')->where(['user_id'=>$this->user_id,'status'=>'guoshi','shop_id'=>$now_location_data['shop_id']])->find();
         
          if($if_exist_cangku){//如果该果实在仓库了
            $new_cangku_data['updatetime'] = time();
            $new_cangku_data['weigh'] = $if_exist_cangku['weigh']+$now_location_data['not_pick_num'];
            $res = Db::name('cangku')->where(['user_id'=>$this->user_id,'status'=>'guoshi','shop_id'=>$now_location_data['shop_id']])->update($new_cangku_data);//修改仓库中该果实的收成
            
          }else{
            $new_cangku_data = Db::name('shop')->where('id',$now_location_data['shop_id'])->field('id as shop_id,image,text,name')->find(); 

            $new_cangku_data['weigh'] = $now_location_data['not_pick_num'];
            $new_cangku_data['updatetime'] = time();
            $new_cangku_data['status'] = 'guoshi';
            $new_cangku_data['user_id'] = $this->user_id;
           
            $res = Db::name('cangku')->insert($new_cangku_data);//插入一条果实到仓库
          }
          if($res){
            Db::name('new_my_plant')->where(['user_id'=>$this->user_id,'location'=>$location])->update(['not_pick_num'=>0]);
          }
          $add_exp = Db::name('new_prop')->where('id',9)->value('add_exp');
          Db::name('user')->where('id',$this->user_id)->setInc('experience',$add_exp);

          $return_text = '采摘了'.$now_location_data['not_pick_num'].'斤';
          break;
          
      }

      $this->up_action();
      $this->success($return_text);

     }

     //自动判断是否满足升级条件
    public function up_action(){

      $level_name_data = Db::name('level')->find(1);
      $level_name_data = json_decode($level_name_data['destination_json'],true);

      $next_level_key = $this->auth->level;//下一等级key
      $next_level = $this->auth->level+1;
      $now_experience = $this->auth->experience;//当前经验值

      $next_level_exp = $level_name_data[$next_level_key]['experience'];//下一等级的经验值
      if($now_experience>=$next_level_exp){//判断当前经验值是否满足升级

        $discount = $level_name_data[$next_level_key]['discount'];
        $land_num = $level_name_data[$next_level_key]['land_num'];

        $shop_data = Db::name('shop')->where(['get_level'=>$next_level])->select();
        if($shop_data){
            $Cangku = new Cangku();
            foreach ($shop_data as $key => $value) {
                $insert_cangku['shop_id'] = $value['id'];
                $insert_cangku['num'] = $value['get_level_num'];
                $insert_cangku['status'] = 'zhongzi';
                $insert_cangku['text'] = $value['text'];
                $insert_cangku['image'] = $value['image'];
                $insert_cangku['name'] = $value['name'];
                $insert_cangku['user_id'] = $this->user_id;
                $insert_cangku['updatetime'] = time(); 

                $now_my_cangku = $Cangku->where(['shop_id'=>$value['id'],'user_id'=>$this->user_id])->find();
                
                if($now_my_cangku){
                  $now_my_cangku->setInc('num',$value['get_level_num']);
                }else{
                  Db::name('cangku')->insert($insert_cangku);
                }
            }

        }
        
        Db::name('user')->where('id',$this->user_id)->update(['level'=>$next_level,'discount'=>$discount,'land_num'=>$land_num]);//新等级
      }

    }
     
     /**
     * 首页种植
     * @ApiSummary  (返回最新的首页数据)
     * @ApiMethod   (POST)
     * @ApiRoute    (/api/index/planting)
     * @ApiParams   (name="location",type=int,required=true,description="位置")
     * @ApiParams   (name="shop_id",type=int,required=true,description="种子id")
     * @ApiReturn({
{
"code": 0,
"msg": "该地已种植种子了",
"time": "1606187173",
"data": null
}

      {
  "code": 1,
  "msg": "请求成功",
  "time": "1606187108",
  "data": {
    "my_data": {
      "avatar": "http://vicky.nongchang2.com/assets/img/avatar.png",
      "experience": "822.00",
      "discount": "9.40",
      "nickname": "u103",
      "land_num": 3,
      "level": "6"
    },
    "index": {
      "1": {
        "id": 2,
        "name": null,
        "user_id": 103,
        "image": "https://nongchang.bidou88.cn/uploads/20200911/8759a5404c4deca3bdf5310d51565a79.jpg",
        "shop_id": 2,
        "now_exp": "232.00",
        "location": "1",
        "not_pick_num": "0.00",
        "shengyu": "8.00",
        "createtime": 1606186676,
        "shou_level": 0
      },
      "2": {
        "id": 3,
        "name": null,
        "user_id": 103,
        "image": "https://nongchang.bidou88.cn/uploads/20200911/8759a5404c4deca3bdf5310d51565a79.jpg",
        "shop_id": 2,
        "now_exp": "0.00",
        "location": "2",
        "not_pick_num": "0.00",
        "shengyu": "240.00",
        "createtime": 1606130942,
        "shou_level": 0
      },
      "3": {
        "id": 4,
        "name": "测试种子",
        "user_id": 103,
        "image": "/assets/img/qrcode.png",
        "shop_id": 1,
        "now_exp": "0.00",
        "location": "3",
        "not_pick_num": "0.00",
        "shengyu": "240.00",
        "createtime": 1606187057,
        "shou_level": 0
      }
    }
  }
}
      })
     */
    public function planting(){
        
        $param = input();
        $param['user_id'] = $this->user_id;
        $location = $param['location'];

        if($this->auth->land_num<Db::name('new_my_plant')->where(['user_id'=>$this->user_id])->count()+1)$this->error('当前土地数量不足');

        $now_location_data = Db::name('new_my_plant')->where(['user_id'=>$this->user_id,'location'=>$location])->find();
        if($now_location_data)$this->error('该地已种植种子了');

        $Cangku = new Cangku();
        $Newmyplant = new Newmyplant();

        $destination_json = Db::name('shop')->where('id',input('shop_id'))->value('destination_json');//查询最近一次成熟需要多少能量值
        if(empty($destination_json))$this->error('当前种子未设置收成');
        $destination_array = json_decode($destination_json,true);

        $param['next_exp'] = $param['shengyu'] = $destination_array[0]['exp'];

        $cangku_data = $Cangku->where(['shop_id'=>input('shop_id'),'user_id'=>$this->user_id])->find();
        if($cangku_data['num']<=0)$this->error('种子数不够了');
      
        $param = array_merge($param,$cangku_data->toArray());

        unset($param['id']);

        $res = $Newmyplant->allowField(true)->save($param);

        if($res){
            // 种子数量减少
            $cangku_data->setDec('num',1);
            $add_exp = Db::name('new_prop')->where('id',7)->value('add_exp');
            Db::name('user')->where('id',$this->user_id)->setInc('experience',$add_exp);
            $this->up_action();
            $this->index();
        }
    }

    /**
     * 果实兑换成余额,捐赠,或者是邮寄到家(传了手机号码就代表邮寄)
     * @param int $shop_id 果实id
     * @param decimal $weigh 果实单位多少斤
     * @param int $address_id 收货地址
     * @param int $status 捐赠:juanzeng,余额:yue,邮寄到家:youji     
     */
    public function change(){
        $status = input('status');
        $weigh = input('weigh');
        $address_id = input('address_id');
        $shop_id = input('shop_id');

        $Cangku = new Cangku();
        $my_cangku = $Cangku->where(['user_id'=>$this->user_id,'shop_id'=>$shop_id,'status'=>'guoshi'])->find();
        if($my_cangku['weigh']<$weigh)$this->error('仓库的果实数量不足');
                
        if($status=='yue'){
          if($weigh<1)$this->error('至少一斤才能兑换余额');
          $out_price = Db::name('shop')->where('id',$shop_id)->value('out_price');
          $price = $weigh/$out_price;

          $insert_yue_log['price'] = $price;
          $insert_yue_log['user_id'] = $this->user_id;
          $insert_yue_log['shop_id'] = $shop_id;
          $insert_yue_log['status'] = 1;
          $insert_yue_log['weigh'] = $weigh;
          $insert_yue_log['text'] = '成功兑换'.$my_cangku['name'].$weigh.'斤';
          $insert_yue_log['createtime'] = time();

          $res = Db::name('yu_log')->insert($insert_yue_log);
          if($res){
            $return_text = '成功兑换'.$price.'元';
            
            Db::name('user')->where('id',$this->user_id)->setInc('money',$price);
          }
          
        }
        if($status=='youji'){
          $insert_order['pay_status']=50;
          $insert_order['weigh'] = $weigh;
          $insert_order['address_id'] = $address_id;
          $insert_order['user_id'] = $this->user_id;
          $insert_order['createtime'] = time();
          $insert_order['updatetime'] = time();
          $insert_order['name'] = $my_cangku['name'];
          $insert_order['image'] = $my_cangku['image'];
          $insert_order['order_no'] = 'youji'.mt_rand(10000000,99999999999);

          $res = Db::name('order')->insert($insert_order);
          $return_text = '成功邮寄到家等待发货';
        }
        if($status=='juanzeng'){
          $juanzeng['weigh'] = $weigh;
          $juanzeng['shop_id'] = $shop_id;
          $juanzeng['user_id'] = $this->user_id;
          $juanzeng['createtime'] = time();
          $res = Db::name('juanzeng')->insert($juanzeng);
          $return_text = '成功捐赠'.$weigh.'斤';
        }
        if($res){
          Db::name('cangku')->where(['user_id'=>$this->user_id,'shop_id'=>$shop_id,'status'=>'guoshi'])->setDec('weigh',$weigh);
        $this->success($return_text);

        }

        
    }



  

    

  

}
